package com.namecard.namecardapi.util;


import com.google.common.hash.BloomFilter;
import com.namecard.namecardapi.constants.BatchConstants;
import com.namecard.namecardapi.constants.ConstantsClass;
import com.namecard.namecardapi.constants.HeadConstants;
import com.namecard.namecardapi.constants.IndexConstants;
import com.namecard.namecardapi.entity.Country;
import com.namecard.namecardapi.entity.LyUser;
import com.namecard.namecardapi.service.CountryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.*;
import java.util.Iterator;
import java.util.List;


@Slf4j
public class CsvUtils {


    /**
     * 解析csv文件并转成bean（方法二）
     *
     * @param filePath csv文件
     * @return 数组
     */
    public static void parsingCsvDataMethod(String filePath, BloomFilter<String> bloomFilter, CountryService countryService) {
//        List<LyUser> lyUserList = new ArrayList<>(20000);

        try (Reader reader = new FileReader(filePath);
             CSVParser csvParser = CSVFormat.DEFAULT
                     .withHeader(
                             HeadConstants.CSV_HEAD
                     )
//                     .withFirstRecordAsHeader()
                     .withIgnoreHeaderCase()
                     .withTrim()
                     .parse(reader)) {
            Iterator<CSVRecord> iterator = csvParser.iterator();
            if (iterator.hasNext()) {
                iterator.next();    //跳过第一行
            }
//            int i = 0;
            //iterator.hasNext()有可能UncheckedIOException
            while (true) {
                try {
                    boolean hasNext = iterator.hasNext();
                    if (!hasNext) {
                        break;
                    }
                } catch (UncheckedIOException e) {
                    continue;
                }

//                if (i > 333) {
//                    System.out.println(i);
//                }
//                i++;
                //赋值代码
                setValue(iterator,bloomFilter,countryService);
            }

        } catch (IOException e) {
            log.error("解析csv文件失败", e);
            throw new RuntimeException("解析csv文件失败");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void setValue(Iterator<CSVRecord> iterator,BloomFilter<String> bloomFilter, CountryService countryService) throws InterruptedException {
        CSVRecord csvRecord = iterator.next();
        if (csvRecord.size() < 62) {
            return;
        }
        //如果用户名是空的话，直接跳过
        if (csvRecord.get(IndexConstants.LyIndexConstants.FULL_NAME).isEmpty()) {
            return;
        }
        LyUser lyUser = new LyUser();
        lyUser.setFullName(checkIsEmptyAndLength(csvRecord.get(IndexConstants.LyIndexConstants.FULL_NAME)));
        if (lyUser.getFullName() == null) {
            return;
        }
        lyUser.setIndustry(checkIsEmptyAndLength(csvRecord.get(IndexConstants.LyIndexConstants.INDUSTRY)));
        lyUser.setJobTitle(checkIsEmptyAndLength(csvRecord.get(IndexConstants.LyIndexConstants.JOB_TITLE)));
        lyUser.setEmail(checkIsEmptyAndLength(csvRecord.get(IndexConstants.LyIndexConstants.EMAILS)));
        lyUser.setMobile(checkIsEmptyAndLength(csvRecord.get(IndexConstants.LyIndexConstants.MOBILE)));
        lyUser.setLocationCountry(checkIsEmptyAndLength(csvRecord.get(IndexConstants.LyIndexConstants.LOCATION_COUNTRY)));
        lyUser.setLocationProvince(checkIsEmptyAndLength(csvRecord.get(IndexConstants.LyIndexConstants.REGION)));
        //判断区域表中是否存在这个国家，不存在的话，就插入
        if (lyUser.getLocationCountry() != null) {
            if (!bloomFilter.mightContain(lyUser.getLocationCountry())) {
                bloomFilter.put(lyUser.getLocationCountry());
                Country country = new Country();
                country.setName(lyUser.getLocationCountry());
                country.setType(ConstantsClass.COUNTRY);
                country.setParentId(null);
                countryService.mySave(country);
            } 
            if (lyUser.getLocationProvince() != null && !bloomFilter.mightContain(lyUser.getLocationProvince())) {
                //判断区域表中是否存在这个省份，不存在的话，就插入
                bloomFilter.put(lyUser.getLocationProvince());
                Country country2 = new Country();
                country2.setName(lyUser.getLocationProvince());
                country2.setType(ConstantsClass.PROVINCE);
                List<Country> byCountryName = countryService.getByCountryName(lyUser.getLocationCountry());
                country2.setParentId(byCountryName.get(0).getId());
                countryService.mySave(country2);
            }
        }
////        //判断行业表中是否存在这个行业，不存在的话，就插入
//        if (lyUser.getIndustry() != null) {
//            if (!bloomFilter.mightContain(lyUser.getIndustry())) {
//                bloomFilter.put(lyUser.getIndustry());
//                IndustryService industryPosition = new IndustryService();
//                industryPosition.setName(lyUser.getIndustry());
//                industryPosition.setType(ConstantsClass.COUNTRY);
//                industryPosition.setParentId(null);
//                industryPositionService.mySave(industryPosition);
//            }
//            //判断行业表中是否存在这个职位，不存在的话，就插入
//            if (lyUser.getJobTitle() != null && !bloomFilter.mightContain(lyUser.getJobTitle())) {
//                bloomFilter.put(lyUser.getJobTitle());
//                IndustryService industryPosition2 = new IndustryService();
//                industryPosition2.setName(lyUser.getJobTitle());
//                industryPosition2.setType(ConstantsClass.PROVINCE);
//                List<IndustryService> byIndustryName = industryPositionService.getByIndustryName(lyUser.getIndustry());
//                industryPosition2.setParentId(byIndustryName.get(0).getId());
//                industryPositionService.mySave(industryPosition2);
//            }
//        }

        //如果邮箱有多个，则取第一个
        if (lyUser.getEmail() != null) {
            String[] split = lyUser.getEmail().split(",");
            if (split.length > 1) {
                lyUser.setEmail(split[0].trim());
            }
        }
//        System.out.println(lyUser);
        BatchConstants.LY_QUEUE.put(lyUser);
    }

    public static String checkIsEmptyAndLength(String str) {
        if (str == null || str.isEmpty()) {
            return null;
        }
        if (str.length() > 255) {
            return str.substring(0, 255);
        }
        return str;
    }

    public static String checkIsEmpty(String str) {
        if (str == null || str.isEmpty()) {
            return null;
        }
        return str;
    }


    public static void main(String[] args) throws FileNotFoundException {
//        parsingCsvDataMethod("D:\\Downloads\\Alabama.csv");
//        lyUserList.forEach(System.out::println);
//        
    }
}
